// 导入 http 模块
const http = require('http')
const fs = require('fs')
const path = require('path')

// 创建服务对象
const server = http.createServer((request, response) => {
  // 获取请求url的路径
  if (request.method !== 'GET') {
    response.statusCode = 405
    response.end('<h1>405 Method Not Allowed</h1>')
    return
  }
  let { pathname } = new URL(request.url, 'http://127.0.0.1')
  // 声明一个变量
  let root = __dirname + '/page'
  // let root = __dirname + '/../'
  // 拼接文件路径
  let filePath = root + pathname
  // 读取文件 fs 异步 API
  fs.readFile(filePath, (err, data) => {
    if (err) {
      console.log(err);

      // 设置字符集
      response.setHeader('content-type', 'text/html;charset=utf-8')
      // 判断错误的代号
      switch (err.code) {
        case 'ENOENT':
          response.statusCode = 404
          response.end('<h1>404 Not Found</h1>')
        case 'EERM':
          response.statusCode = 403
          response.end('<h1>403 Forbidden</h1>')
        default:
          response.status = 500
          response.end('<h1>Internal Server Error</h1>')
      }

      return
    }
    // 获取文件后缀名
    // let ext = path.extname(filePath).slice(1)
    // console.log(ext);

    // 响应文件内容
    response.end(data)
  })
})


// 监听端口，启动服务
server.listen(9000, () => {
  console.log('服务已经启动...');
})